from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import re

def get_ssh_addr():

    # 配置 WebDriver 的路径
    driver_path = 'D:\\Program Files (x86)\\ChromeWebDriver\\125\\chromedriver.exe'  # 替换为你的 ChromeDriver 路径
    


    # 替换为您使用的 WebDriver（例如 Chrome, Firefox 等）
    options = webdriver.ChromeOptions()
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")

    driver = webdriver.Chrome(driver_path,options=options)


    # 打开登录页面
    driver.get('https://dashboard.cpolar.com/login')

    # 等待页面加载
    time.sleep(2)

    # 输入用户名和密码，替换为实际的元素选择器和登录信息
    username_input = driver.find_element(By.NAME, 'login')  # 替换为实际的用户名输入框的选择器
    password_input = driver.find_element(By.NAME, 'password')  # 替换为实际的密码输入框的选择器

    username_input.send_keys('jack911jie@qq.com')  # 替换为实际的用户名
    password_input.send_keys('fwlic0523')  # 替换为实际的密码

    # 提交登录表单
    password_input.send_keys(Keys.RETURN)

    time.sleep(2)

    # 打开需要访问的页面
    # driver.get('https://www.baidu.com')
    driver.get('https://dashboard.cpolar.com/status')

    # 等待页面加载
    time.sleep(2)

    page_source = driver.page_source
    # print(page_source)

    # 正则表达式查找符合条件的字符串
    pattern = r'tcp://[^ ]*cpolar[^ ]*\d'
    matches = re.findall(pattern, page_source)

    if matches:
        match=matches[0]


    # 关闭浏览器
    driver.quit()

    return match

def update_config(res):
    if res=='':
        res='tcp://1.tcp.cpolar.cn:22344'
    
    res_arr=res.split(':')
    ip=f'HostName {res_arr[1][2:]}'
    port=f'port {res_arr[2]}'

    print(f'\n获取的ip地址及端口：\n{ip}\n{port}')

    with open('c:\\Users\\admin\\.ssh\\config','r',encoding='utf-8') as f:
        lines=f.readlines()
    
    updated_lines=[]
    count_hostname=0
    count_port=0

    for line in lines[0:5]:
        if re.match('Host[Nn]ame\s+\d{1,3}\.tcp\.cpolar.\w+',line) and count_hostname==0:
            # print('match 1 hostname')
            line=re.sub('Host[Nn]ame\s+\d{1,3}\.tcp\.cpolar.\w+',ip,line)          
            updated_lines.append(line)  
            count_hostname+=1
        elif re.match('port\s+\d{5}$',line) and count_port==0:
            # print('match 1 port')
            line=re.sub('port\s+\d{5}$',port,line)          
            updated_lines.append(line)  
            count_port+=1
        else:
            # print('match 0')
            updated_lines.append(line)
    for line in lines[5:]:
        updated_lines.append(line)

    with open('c:\\Users\\admin\\.ssh\\config','w',encoding='utf-8') as f:
        f.writelines(updated_lines)
    
    # print(updated_lines)
    print('更新完成')


if __name__=='__main__':
    res=get_ssh_addr()
    # update_config(res='tcp://1.tcp.cpolar.cn:22344')
    update_config(res=res)